package com.xuxx.sso.passport.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xuxx.sso.bean.UserInfo;
import com.xuxx.sso.passport.config.Properties;
import com.xuxx.sso.service.AuthService;
import com.xuxx.sso.service.UserService;
import com.xuxx.sso.util.CookieUtils;
import com.xuxx.sso.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * ==========================
 * Created with IntelliJ IDEA.
 * User: 徐兴兴
 * Date: 2019/5/15
 * Time: 18:06
 * ==========================
 */
@Controller
public class IndexController
{
	@Reference
	private AuthService authService;

	@Reference
	private UserService userService;

	@Autowired
	private Properties properties;

	@RequestMapping("login")
	public String login()
	{
		return "login";
	}

	@RequestMapping("valid")
	@ResponseBody
	public Object valid(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String token = CookieUtils.getCookieValue(request, "user-token");
		try {
			Claims claims = JwtUtil.parseJWT(token, properties.salt);
			String id = claims.get("id", String.class);

		} catch (Exception e) {
			e.printStackTrace();
			if (e instanceof ExpiredJwtException) {
				//证书过期，重定向到登录页面

				response.sendRedirect("/login");
			}else{
				//证书错误
				response.sendRedirect("/login");
			}

			return null;
		}

//		return authService.auth(username,password, );
		return null;
	}

	@RequestMapping("doLogin")
	public ModelAndView doLogin(String username, String password,HttpServletRequest request,HttpServletResponse response,
								ModelAndView modelAndView) throws IOException {
		UserInfo userInfo = userService.findByUserNameAndPassword(username, password);
		if (userInfo == null)
		{
			//账号密码错误
			modelAndView.setViewName("login");
			modelAndView.addObject("errormsg","账号或密码错误");
			return modelAndView;
		}
//		String requestURI = request.getRequestURI();
//		if (StringUtils.isBlank(requestURI) || "/".equals(requestURI))
//		{
//			response.sendRedirect("http://w\");
//		}else{
//
//		}

		response.sendRedirect("http://www.baidu.com");
		return null;
	}

}
